package com.esoon.chatarea;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.ThumbnailUtils;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;

import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;

import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.esoon.smartsee.R;
import com.esoon.socketio.api.WebChatIM;
import com.esoon.tools.EntityVideo;
import com.esoon.tools.FileUtils;
import com.esoon.tools.Tools;
import com.esoon.view.AudioRecordButton;
import com.leon.lfilepickerlibrary.LFilePicker;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import io.socket.emitter.Emitter;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private ImageView imageView;
    private ImageButton getimage;

    /*creatFileView*/
    private ImageButton filepic;
    private TextView filestoragetxt;
    private TextView filenametxt;

    /*sendfilebutton*/
    private ImageButton filesend;
    private ImageButton imagesend;
    private ImageButton videosend;

    private ImageButton button_add;
    private ImageButton button_face;
    private ImageButton button_voice;
    private ImageButton wechaelse;
    private ImageButton button_voice2;
    private ImageButton button_add2;

    private ImageView showimage;
    private TextView textView;
    private ScrollView chatscrol;
    private LinearLayout linerView;
    private TextView editText;
    private TextView chattext;
    private RelativeLayout holelayout;
    private RelativeLayout choicelayout;
    private Handler handler;
    private Button button_back;
    private Timer timer;
    private LinearLayout viocelayout;
    private LinearLayout sendchatlayout;
    private HorizontalListView video_scroll_ayout;
    private AudioRecordButton button;
    private final int EX_FILE_PICKER_RESULT = 0xfa01;
    private String startDirectory = null;// 记忆上一次访问的文件目录路径
    private MediaPlayer mediaPlayer;
    private static final int IMAGE = 1;
    private int count = 0;
    private boolean flag = true;
    private boolean textflag = false;
    private int voicecount = 0;
    private static final String TAG = "MainActivity";
    private ArrayList<Object> list = new ArrayList<>();
    private ArrayList<Object> imaginlist = new ArrayList<>();
    private SharedPreferences sharedPreferences = null;
    private SharedPreferences.Editor editor = null;
    private String filepath;
    private boolean aniflag = true;
    private boolean videoflag = true;
    private BaseAdapter adapter;
    private List<EntityVideo> sysVideoList;
    private GridView gridview;
    private List<String> Videolist;
    private SimpleAdapter simpleAdapter;
    private List<Map<String, Object>> imglist = new ArrayList<>();
    private boolean faceflag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainlayout);
        initView();
        initData();

    }

    private View creatFileView(int source, String filename, String msgtype, int length) {
        View view = null;
        LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
        view = layoutInflater.inflate(source, null);
        filenametxt = (TextView) view.findViewById(R.id.filename);
        filestoragetxt = (TextView) view.findViewById(R.id.filestorage);
        filepic = (ImageButton) view.findViewById(R.id.filepic);
        if (msgtype.equals("voice")) {
            filepic.setImageResource(R.drawable.voiceplayer);
            filepic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    filepic.setImageResource(R.drawable.voiceplayerwhite);
                    openFileExplorer();
                }
            });

        } else if (msgtype.equals("file")) {
            filepic.setImageResource(R.drawable.fileget);
            filepic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    filepic.setImageResource(R.drawable.voiceplayerwhite);
                    openFileExplorer();
                }
            });
        } else if (msgtype.equals("video")) {
            filepic.setImageResource(R.drawable.videoget);
            filepic.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    filepic.setImageResource(R.drawable.voiceplayerwhite);
                    openFileExplorer();
                }
            });
        }
        filenametxt.setText(filename);
        filestoragetxt.setText(length % 1024 + "kb");
        return view;
    }

    private View creatVoiceView(int voicelayout, final int seconds, final String filepath) {
        View view = null;


        LayoutInflater layoutInflater = LayoutInflater.from(this);
        view = layoutInflater.inflate(voicelayout, null);
        ImageView voicepalyerview = (ImageView) view.findViewById(R.id.voicepalyerview);
        TextView voicelengthtext = (TextView) view.findViewById(R.id.voicelengthtext);
        RelativeLayout voicepalyerlayout = (RelativeLayout) view.findViewById(R.id.voicepalyerlayout);
        final AnimationDrawable avoiceplayer = (AnimationDrawable) voicepalyerview.getBackground();

        voicepalyerlayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                voicecount = 0;
                if (aniflag) {
                    avoiceplayer.start();
                    mediaPlayer = new MediaPlayer();
                    try {
                        mediaPlayer.setDataSource(filepath);
                        mediaPlayer.prepare();
                        mediaPlayer.start();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                    timer = new Timer();
                    timer.schedule(new TimerTask() {
                        @Override
                        public void run() {
                            if (voicecount == 0) {
                                avoiceplayer.stop();

                                aniflag = true;
                                Log.e(TAG, "timer");
                                mediaPlayer.stop();
                                timer.cancel();


                            }
                        }
                    }, seconds * 1000);

                } else {
                    avoiceplayer.stop();
                    voicecount = 1;
                    timer.cancel();
                    mediaPlayer.stop();
                }
                aniflag = !aniflag;

            }
        });
        voicelengthtext.setText(seconds + "s“");
        return view;

    }

    private View creatSendFileView(int source, final String filename, int filesize, String msgtype) {
        View view = null;
        LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
        view = layoutInflater.inflate(source, null);
        TextView filesize_text = view.findViewById(R.id.filesize_text);
        TextView filename_text = view.findViewById(R.id.filename_text);
        ImageView file_video = view.findViewById(R.id.filepic_imag);
        filename_text.setText(new File(filename).getName());
        filesize_text.setText(filesize / 1024 + "kb");
        if (msgtype.equals("video")) {
            file_video.setImageBitmap(ThumbnailUtils.createVideoThumbnail(filename, MediaStore.Video.Thumbnails.MICRO_KIND));
        }

        file_video.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Uri uri = Uri.parse(filename);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setDataAndType(uri, "video/mp4");
                startActivity(intent);
            }
        });
        return view;

    }

    private View creatView(int source, String imagename) {

        View view = null;
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        view = inflater.inflate(source, null);
        if (count >= 1) {
            textView = (TextView) view.findViewById(R.id.chatmsg);
            imageView = (ImageView) view.findViewById(R.id.chatimg);
            imageView.setImageResource((Integer) imaginlist.get(count - 1));
            textView.setText((String) list.get(count - 1));
        }
        if (!imagename.isEmpty()) {
            getimage = (ImageButton) view.findViewById(R.id.getimage);
            getimage.setImageURI(Uri.fromFile(new File(FileUtils.getSDCardPath() + imagename)));

        }
        return view;
    }

    private Emitter.Listener mylisetenr = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            try {
                if (!"".equals(args[0]) || args[0] != null) {
                    Log.e("server data :", args[0].toString());
                }
            } catch (Exception e) {
            }
            Message message = new Message();
            message.what = 1;
            message.obj = args[0];
            handler.sendMessage(message);
        }
    };
    private Emitter.Listener openlisetenr = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Log.e(TAG, "socket 连接成功");
            Message message = new Message();
            message.what = 10;
            handler.sendMessage(message);
        }
    };
    private Emitter.Listener closelisetenr = new Emitter.Listener() {
        @Override
        public void call(Object... args) {
            Message message = new Message();
            message.what = 11;
            handler.sendMessage(message);
            Log.e(TAG, "socket 连接断开");
        }
    };

    private void initView() {
        if (sharedPreferences == null) {
            sharedPreferences = getSharedPreferences("socketio", MODE_PRIVATE);
        }
        editor = sharedPreferences.edit();
        button_back = (Button) findViewById(R.id.button_back);
        linerView = (LinearLayout) findViewById(R.id.chatlayout);
        button_add = (ImageButton) findViewById(R.id.button_add);
        button_face = (ImageButton) findViewById(R.id.button_face);
        button_voice = (ImageButton) findViewById(R.id.button_voice);
        chattext = (TextView) findViewById(R.id.edit_sendchat);
        editText = (EditText) findViewById(R.id.edit_sendchat);
        wechaelse = (ImageButton) findViewById(R.id.wechaelse);
        holelayout = (RelativeLayout) findViewById(R.id.holelayout);
        chatscrol = (ScrollView) findViewById(R.id.chatscrol);
        //  button_face = (ImageButton) findViewById(R.id.button_face);
        button_voice2 = (ImageButton) findViewById(R.id.button_voice2);
        choicelayout = (RelativeLayout) findViewById(R.id.choicelayout);
        viocelayout = (LinearLayout) findViewById(R.id.viocelayout);
        sendchatlayout = (LinearLayout) findViewById(R.id.sendchatlayout);
        video_scroll_ayout = (HorizontalListView) findViewById(R.id.video_scroll_ayout);
        gridview = (GridView) findViewById(R.id.gridview);
        filesend = (ImageButton) findViewById(R.id.filesend);
        imagesend = (ImageButton) findViewById(R.id.imagesend);
        videosend = (ImageButton) findViewById(R.id.videosend);
        button_add2 = (ImageButton) findViewById(R.id.button_add2);

        button_back.setOnClickListener(this);
        button_face.setOnClickListener(this);
        button_add.setOnClickListener(this);
        wechaelse.setOnClickListener(this);
        button_voice.setOnClickListener(this);
        filesend.setOnClickListener(this);
        imagesend.setOnClickListener(this);
        videosend.setOnClickListener(this);
        button_voice2.setOnClickListener(this);
        button_add2.setOnClickListener(this);
        video_scroll_ayout.setVisibility(View.GONE);
        choicelayout.setVisibility(View.GONE);
        viocelayout.setVisibility(View.GONE);
        gridview.setVisibility(View.GONE);
        adapter = new BaseAdapter() {
            @Override
            public int getCount() {
                return Videolist.size();
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
                convertView = layoutInflater.inflate(R.layout.videolayout, null);
                ImageView videoview = convertView.findViewById(R.id.vide_imageview);
                TextView videotext = convertView.findViewById(R.id.videtext);
                videoview.setImageBitmap(ThumbnailUtils.createVideoThumbnail(Videolist.get(position), MediaStore.Video.Thumbnails.MICRO_KIND));
                videotext.setText(new File(Videolist.get(position)).getName());

                videoview.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        sendVideo(Videolist.get(position));
                        linerView.addView(creatSendFileView(R.layout.sendfilelayout, Videolist.get(position), (int) new File(Videolist.get(position)).length(), "video"));
                    }
                });


                return convertView;
            }
        };

        button = (AudioRecordButton) findViewById(R.id.recordButton);

        button.setAudioFinishRecorderListener(new AudioRecordButton.AudioFinishRecorderListener() {

            @Override
            public void onFinished(float seconds, String filePath) {
                // TODO Auto-generated method stub
                Recorder recorder = new Recorder(seconds, filePath);
                Log.e(TAG, "声音框没有了");

                viocelayout.setVisibility(View.GONE);
                sendchatlayout.setVisibility(View.VISIBLE);
                Log.e(TAG, filePath);

                //  changeAmrToMp3(filePath,FileUtils.getSDCardPath() + countNum+"recordd.mp3");


                sendVoice(filePath);
                linerView.addView(creatVoiceView(R.layout.voicelayout, (int) seconds, filePath));

            }
        });

        // video_scroll_ayout.setVisibility(View.GONE);
        linerView.setOnTouchListener(new View.OnTouchListener() {


            public boolean onTouch(View arg0, MotionEvent arg1) {

                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                choicelayout.setVisibility(View.GONE);
                return imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);


            }

        });
        holelayout.setOnTouchListener(new View.OnTouchListener() {


            public boolean onTouch(View arg0, MotionEvent arg1) {

                InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                choicelayout.setVisibility(View.GONE);
                return imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

            }

        });
        chattext.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

                button_add.setImageResource(R.drawable.sendbutton);
                flag = false;
                textflag = true;


            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (chattext.getText().toString().equals("")) {

                    button_add.setImageResource(R.drawable.wechatadd);
                }
            }
        });


    }

    private void initData() {

        String[] from = {"img", "text"};
        int[] to = {R.id.img, R.id.text};
        int icon[] = {R.drawable.i0, R.drawable.i1, R.drawable.i2, R.drawable.i3, R.drawable.i4, R.drawable.i5, R.drawable.i6, R.drawable.i7, R.drawable.i8, R.drawable.i9, R.drawable.i10, R.drawable.i11, R.drawable.i12, R.drawable.i13, R.drawable.i14, R.drawable.i15, R.drawable.i16, R.drawable.i17, R.drawable.i18, R.drawable.i19, R.drawable.i20, R.drawable.i21, R.drawable.i22, R.drawable.i23, R.drawable.i24, R.drawable.i25, R.drawable.i26, R.drawable.i27, R.drawable.i28, R.drawable.i29, R.drawable.i30, R.drawable.i31,
                R.drawable.i32, R.drawable.i33, R.drawable.i34, R.drawable.i35, R.drawable.i36, R.drawable.i37, R.drawable.i38, R.drawable.i39, R.drawable.i40, R.drawable.i41, R.drawable.i42, R.drawable.i43, R.drawable.i44, R.drawable.i45, R.drawable.i46, R.drawable.i47, R.drawable.i48, R.drawable.i49, R.drawable.i50, R.drawable.i51, R.drawable.i52, R.drawable.i53, R.drawable.i54, R.drawable.i55, R.drawable.i56, R.drawable.i57, R.drawable.i58, R.drawable.i59, R.drawable.i60, R.drawable.i61, R.drawable.i62, R.drawable.i63, R.drawable.i64, R.drawable.i65, R.drawable.i66, R.drawable.i67, R.drawable.i68, R.drawable.i69, R.drawable.i70, R.drawable.i71, R.drawable.i72, R.drawable.i73, R.drawable.i74, R.drawable.i75, R.drawable.i76, R.drawable.i77, R.drawable.i78, R.drawable.i79, R.drawable.i80, R.drawable.i81, R.drawable.i82, R.drawable.i83, R.drawable.i84, R.drawable.i85, R.drawable.i86, R.drawable.i87, R.drawable.i88, R.drawable.i89, R.drawable.i90, R.drawable.i91, R.drawable.i92, R.drawable.i93, R.drawable.i94, R.drawable.i95, R.drawable.i96, R.drawable.i97, R.drawable.i98, R.drawable.i99, R.drawable.i100, R.drawable.i101, R.drawable.i102, R.drawable.i103, R.drawable.i104, R.drawable.i105, R.drawable.i106, R.drawable.i107, R.drawable.i108, R.drawable.i109, R.drawable.i110, R.drawable.i111, R.drawable.i112, R.drawable.i113, R.drawable.i114, R.drawable.i115, R.drawable.i116, R.drawable.i117, R.drawable.i118, R.drawable.i119, R.drawable.i120, R.drawable.i121, R.drawable.i122, R.drawable.i123, R.drawable.i124, R.drawable.i125, R.drawable.i126, R.drawable.i127, R.drawable.i128, R.drawable.i129, R.drawable.i130, R.drawable.i131, R.drawable.i132};

        String name[] = {"/::)",
                "/::~",
                "/::B",
                "/::|",
                "/:8-)",
                "/::&lt;",
                "/::$",
                "/::X",
                "/::Z",
                "/::&#39;(",
                "/::-|",
                "/::@",
                "/::P",
                "/::D",
                "/::O",
                "/::(",
                "[囧]",
                "/::Q",
                "/::T",
                "/:,@P",
                "/:,@-D",
                "/::d",
                "/:,@o",
                "/::g",
                "/:|-)",
                "/::!",
                "/::L",
                "/::&gt;",
                "/::,@",
                "/:,@f",
                "/::-S",
                "/:?",
                "/:,@x",
                "/:,@@",
                "/::8",
                "/:,@!",
                "/:!!!",
                "/:xx",
                "/:bye",
                "/:wipe",
                "/:dig",
                "/:handclap",
                "/:&-(",
                "/:B-)", "/:&lt;@",
                "/:@&gt;",
                "/::-O",
                "/:&gt;-|",
                "/:P-(",
                "/::&#39;|",
                "/:X-)",
                "/::*",
                "/:@x",
                "/:8*",
                "/:pd",
                "/:&lt;W&gt;",
                "/:beer",
                "/:basketb",
                "/:oo",
                "/:coffee",
                "/:eat",
                "/:pig",
                "/:rose",
                "/:fade",
                "/:showlove",
                "/:heart",
                "/:break",
                "/:cake",
                "/:li",
                "/:bome",
                "/:kn",
                "/:footb",
                "/:ladybug",
                "/:shit",
                "/:moon",
                "/:sun",
                "/:gift",
                "/:hug",
                "/:strong",
                "/:weak",
                "/:share",
                "/:v",
                "/:@)",
                "/:jj",
                "/:@@",
                "/:bad",
                "/:lvu",
                "/:no", "/:ok",
                "/:love",
                "/:&lt;L&gt;",
                "/:jump",
                "/:shake",
                "/:&lt;O&gt;",
                "/:circle",
                "/:kotow",
                "/:turn",
                "/:skip",
                "/:oY",
                "/:#-0",
                "/:hiphot",
                "/:kiss",
                "/:&lt;&",
                "/:&&gt;",
                "/::+"};


        for (int i = 0; i < 105; i++) {
            Map<String, Object> map = new HashMap<>();
            map.put("img", icon[i]);
            map.put("text", name[i]);
            imglist.add(map);
        }
        simpleAdapter = new SimpleAdapter(this, imglist, R.layout.gridviewlayout, from, to);
        gridview.setAdapter(simpleAdapter);
        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                WebChatIM.WebChatAndroid.getInstance().sendTextMessage( editText.getText().toString());



            }
        });

        handler = new Handler() {

            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                switch (msg.what) {

                    case 1:

                        try {
                            JSONObject jsonObject = (JSONObject) msg.obj;
                            String msgType = jsonObject.getString("msgType");
                            if (msgType.equals("text")) {

                                String recieveContent = jsonObject.getJSONObject("text").getString("content");
                                list.add(recieveContent);
                                imaginlist.add(R.drawable.server);
                                count++;
                                linerView.addView(creatView(R.layout.serverlayout, ""));
                            } else if (msgType.equals("image")) {

                                String mediaId = jsonObject.getJSONObject("image").getString("mediaId");
                                Log.e(TAG, "getmsg is image");
                                WebChatIM.WebChatAndroid.getInstance().downFile(handler, mediaId, "image");
                            } else if (msgType.equals("file")) {

                                String mediaId = jsonObject.getJSONObject("file").getString("mediaId");

                                WebChatIM.WebChatAndroid.getInstance().downFile(handler, mediaId, "file");
                                Log.e(TAG, "getmsg is file");
                            } else if (msgType.equals("voice")) {

                                String mediaId = jsonObject.getJSONObject("voice").getString("mediaId");

                                WebChatIM.WebChatAndroid.getInstance().downFile(handler, mediaId, "voice");
                                Log.e(TAG, "getmsg is voice");
                            } else if (msgType.equals("video")) {

                                String mediaId = jsonObject.getJSONObject("video").getString("mediaId");

                                WebChatIM.WebChatAndroid.getInstance().downFile(handler, mediaId, "video");
                                Log.e(TAG, "getmsg is video");
                            }

                        } catch (Exception e) {

                            //   chatArea.setText(chatArea.getText()+"\n"+"服务端连接成功");
                            e.printStackTrace();
                        }
                        break;

                    case 2:
                        String mediaId = null;
                        JSONObject jsonObject = (JSONObject) msg.obj;

                        try {
                            mediaId = jsonObject.getJSONObject("data").getString("mediaId");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        WebChatIM.WebChatAndroid.getInstance().sendFileMessage( new File(filepath).getName(), mediaId);
                        break;

                    case 3:
                        String imagemediaId = null;
                        JSONObject ijsonObject = (JSONObject) msg.obj;

                        try {
                            imagemediaId = ijsonObject.getJSONObject("data").getString("mediaId");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        WebChatIM.WebChatAndroid.getInstance().sendImageMessage( imagemediaId);

                        break;
                    case 4:
                        String voicemediaId = null;
                        JSONObject voicejsonObject = (JSONObject) msg.obj;

                        try {
                            voicemediaId = voicejsonObject.getJSONObject("data").getString("mediaId");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        Log.e("handler voice", "send");
                        WebChatIM.WebChatAndroid.getInstance().sendVoiceMessage( voicemediaId);

                        break;
                    case 5:
                        String videomediaId = null;
                        JSONObject videojsonObject = (JSONObject) msg.obj;

                        try {
                            videomediaId = videojsonObject.getJSONObject("data").getString("mediaId");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        WebChatIM.WebChatAndroid.getInstance().sendVideoMessage(videomediaId);

                        Log.e("handler video", "send");

                        break;
                    case 6:
                        list.add((String) msg.obj);
                        imaginlist.add(R.drawable.server);
                        count++;
                        linerView.addView(creatView(R.layout.serverlayout, (String) msg.obj));
                        Log.e("handler image", (String) msg.obj);

                        break;

                    case 7:

                        linerView.addView(creatFileView(R.layout.filelayout, (String) msg.obj, "voice", msg.arg1));
                        Log.e("handler voice", (String) msg.obj);
                        list.add("语音下载成功");
                        imaginlist.add(R.drawable.server);
                        count++;
                        linerView.addView(creatView(R.layout.serverlayout, ""));

                        break;

                    case 8:
                        linerView.addView(creatFileView(R.layout.filelayout, (String) msg.obj, "video", msg.arg1));
                        Log.e("handler voice", (String) msg.obj);
                        list.add("视频下载成功");
                        imaginlist.add(R.drawable.server);
                        count++;
                        linerView.addView(creatView(R.layout.serverlayout, ""));
                        break;
                    case 9:
                        linerView.addView(creatFileView(R.layout.filelayout, (String) msg.obj, "file", msg.arg1));
                        Log.e("handler voice", (String) msg.obj);
                        list.add("文件下载成功");
                        imaginlist.add(R.drawable.server);
                        count++;
                        linerView.addView(creatView(R.layout.serverlayout, ""));
                        break;

                    case 10:
                        Toast.makeText(MainActivity.this, "连接成功", Toast.LENGTH_LONG).show();
                        break;
                    case 11:
                        Toast.makeText(MainActivity.this, "连接断开", Toast.LENGTH_LONG).show();
                        break;
                }

            }


        };

        if (Tools.isNetworkConnected(this)) {
            try {
                WebChatIM.WebChatAndroid.getInstance().connect("123", "https", sharedPreferences.getString("address", "47.103.37.228:80"),"47.103.37.228", "M_lXMiQRb7_2KT_pHH3TI_T_NoSc3y_v_F9YaaNBnv_","","", mylisetenr, openlisetenr, closelisetenr);

            } catch (Exception e) {
                Toast.makeText(MainActivity.this, "地址错误，请重新设置", Toast.LENGTH_LONG).show();
            }


        } else {
            Toast.makeText(this, "初始化失败请检查网络设置", Toast.LENGTH_LONG).show();

        }
        //  ChatInterface.ChatOnline.getInstance().connect("http://sit.esooncloud.com:9081/", new IO.Options(), mylisetenr);


    }

    private void sendTextMsg() {
        if (!chattext.getText().toString().equals("")) {
            list.add(chattext.getText().toString());

            imaginlist.add(R.drawable.icon);
            count++;
            linerView.addView(creatView(R.layout.customerlayout, ""));
            chatscrol.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    chatscrol.post(new Runnable() {
                        public void run() {
                            chatscrol.fullScroll(View.FOCUS_DOWN);
                        }
                    });
                }
            });
            WebChatIM.WebChatAndroid.getInstance().sendTextMessage( editText.getText().toString());

            editText.setText("");
        }

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //获取图片路径
        if (requestCode == IMAGE && resultCode == Activity.RESULT_OK && data != null) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String Path = c.getString(columnIndex);
            if (Path.endsWith("png") || Path.endsWith("jpg")) {

                showImage(Path, "image");
            } else if (Path.endsWith("mp4")) {

                showImage(Path, "video");
            } else if (Path.endsWith("mp3")) {

            } else {

                showImage(Path, "file");
            }
            c.close();
        }


        if (requestCode == EX_FILE_PICKER_RESULT) {

            List<String> list = data.getStringArrayListExtra("paths");
            Toast.makeText(getApplicationContext(), "选中了" + list.size() + "个文件", Toast.LENGTH_SHORT).show();
            //如果是文件夹选择模式，需要获取选择的文件夹路径
            String path = data.getStringExtra("path");

            startDirectory = path;
            filepath = path;
            sendFile(path);

            File f = new File(path);

            linerView.addView(creatSendFileView(R.layout.sendfilelayout, f.getName(), (int) f.length(), "file"));

        }

    }

    //加载本地图片
    private void showImage(String path, String msgtype) {
        Bitmap bm = BitmapFactory.decodeFile(path);
        View view = null;
        LayoutInflater inflater = LayoutInflater.from(MainActivity.this);
        view = inflater.inflate(R.layout.sendimagelayout, null);
        textView = (TextView) view.findViewById(R.id.chatmsg);
        imageView = (ImageView) view.findViewById(R.id.chatimg);
        showimage = (ImageView) view.findViewById(R.id.showimage);
        imageView.setImageResource(R.drawable.icon);

        if (!path.isEmpty()) {
            showimage.setImageBitmap(bm);

        }
        if (msgtype.equals("image")) {
            sendImage(path);
        } else if (msgtype.equals("video")) {
            sendVideo(path);
        } else if (msgtype.equals("file")) {
            sendFile(path);
        }
        linerView.addView(view);


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_add:
                if (flag) {

                    choicelayout.setVisibility(View.VISIBLE);
                    flag = false;

                } else {
                    button_add.setImageResource(R.drawable.wechatadd);
                    choicelayout.setVisibility(View.GONE);
                    flag = true;
                }

                video_scroll_ayout.setVisibility(View.GONE);
                sendTextMsg();


                break;
            case R.id.wechaelse:
                callAgent();
                break;

            case R.id.button_face:
                // sendImage();
                // sendVideo();

                if (faceflag) {
                    gridview.setVisibility(View.VISIBLE);
                    faceflag = false;
                } else {
                    gridview.setVisibility(View.GONE);
                    faceflag=true;
                }


                break;
            case R.id.button_voice:
                //sendFile();

                sendchatlayout.setVisibility(View.GONE);
                viocelayout.setVisibility(View.VISIBLE);
                break;
            case R.id.button_voice2:
                viocelayout.setVisibility(View.GONE);
                sendchatlayout.setVisibility(View.VISIBLE);

                break;
            case R.id.button_back:
                final AlertDialogCommon alertDialogCommon = new AlertDialogCommon(MainActivity.this, R.layout.addresslayout);
                alertDialogCommon.showDialog();
                Button submit = alertDialogCommon.getView().findViewById(R.id.button_submit);
                Button cancel = alertDialogCommon.getView().findViewById(R.id.button_cancel);
                final EditText editText = alertDialogCommon.getView().findViewById(R.id.addresstext);
                editText.setText(sharedPreferences.getString("address", "47.103.37.228:80"));
                submit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        editor.putString("address", editText.getText().toString());
                        editor.commit();
                        alertDialogCommon.dismiss();
                        try {
                            WebChatIM.WebChatAndroid.getInstance().ondisconnect("message", mylisetenr);
                            WebChatIM.WebChatAndroid.getInstance().connect("123", "https", sharedPreferences.getString("address", "47.103.37.228:80"),"47.103.37.228:80", "M_lXMiQRb7_2KT_pHH3TI_T_NoSc3y_v_F9YaaNBnv_","","", mylisetenr, openlisetenr, closelisetenr);


                        } catch (Exception e) {
                            Toast.makeText(MainActivity.this, "地址:" + sharedPreferences.getString("address", "sit.esooncloud.com:9081") + "错误请重新输入", Toast.LENGTH_LONG).show();
                        }
                        Toast.makeText(MainActivity.this, "开始重新连接:" + sharedPreferences.getString("address", "sit.esooncloud.com:9081"), Toast.LENGTH_LONG).show();
                    }
                });
                cancel.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        alertDialogCommon.dismiss();
                    }
                });
                break;
            case R.id.button_add2:
                if (flag) {

                    choicelayout.setVisibility(View.VISIBLE);

                } else {
                    choicelayout.setVisibility(View.GONE);

                }

                flag = !flag;
                break;
            case R.id.filesend:

                int REQUESTCODE_FROM_ACTIVITY = 1000;
                new LFilePicker()
                        .withActivity(MainActivity.this)
                        .withRequestCode(REQUESTCODE_FROM_ACTIVITY)
                        .withStartPath(Environment.getExternalStorageDirectory().getPath())//指定初始显示路径
                        .withIsGreater(false)//过滤文件大小 小于指定大小的文件
                        .withFileSize(5000 * 1024)//指定文件大小为500K
                        .start();

                break;
            case R.id.imagesend:
                Intent intent = new Intent(Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(intent, 1);

                break;
            case R.id.videosend:
                Log.e(TAG, "i111");

                choicelayout.setVisibility(View.GONE);
                video_scroll_ayout.setVisibility(View.VISIBLE);
                getVideoFromSDCard(MainActivity.this);
                video_scroll_ayout.setAdapter(adapter);

              /*  for (int i = i0; i < Videolist.size(); i++) {
                    LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
                    View videoview = layoutInflater.inflate(R.layout.videolayout, video_scroll_ayout, false);
                    ImageView videoImageview = videoview.findViewById(R.id.vide_imageview);
                    TextView textView = (TextView) videoview.findViewById(R.id.videtext);
                    textView.setText(new File(Videolist.get(i)).getName());
                    videouri = Videolist.get(i);
                  //  File file = new File(sysVideoList.get(i).getPath());
                    bitmap= ThumbnailUtils.createVideoThumbnail(videouri, MediaStore.Video.Thumbnails.MICRO_KIND);
                  //  fileUri = Uri.fromFile(file);
                    videoImageview.setImageBitmap(bitmap);
                    videoImageview.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            sendVideo(videouri);
                            gridView.addView(creatSendFileView(R.layout.sendfilelayout, videouri, (int) new File(videouri).length(), "video"));
                        }
                    });
                    video_scroll_ayout.addView(videoview);
                }

              //  Log.e(TAG, sysVideoList.get(i1).getPath());
                flag = !flag;*/
                break;


        }
    }

    private void sendVideo(String filepath) {

        WebChatIM.WebChatAndroid.getInstance().sendVideoData(handler, new File(filepath));
    }

    private void callAgent() {

        WebChatIM.WebChatAndroid.getInstance().callAgentService( );
        Log.e(TAG, "callAgent");
    }

    private void sendVoice(String filepath) {

        WebChatIM.WebChatAndroid.getInstance().sendVoiceData(handler, new File(filepath));
    }

    private void sendImage(String path) {


        WebChatIM.WebChatAndroid.getInstance().sendImageData(handler, new File(path));
        Log.e(TAG, "sendImage");
    }

    private void sendFile(String path) {


        File file = new File(path);
        WebChatIM.WebChatAndroid.getInstance().uploadFile(handler, file);

    }

    private File getFile() {

        File mFile = new File("/mnt/sdcard/mmmmmmm.txt");
        //判断文件是否存在，存在就删除
        if (mFile.exists()) {
            mFile.delete();
        }
        try {
            //创建文件
            mFile.createNewFile();
            //给一个吐司提示，显示创建成功
            Toast.makeText(getApplicationContext(), "文件创建成功", Toast.LENGTH_SHORT).show();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mFile;
    }

    private void openFileExplorer() {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        //系统调用Action属性
        intent.setType("*/*");
        //设置文件类型
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        // 添加Category属性
        try {
            startActivity(intent);
        } catch (Exception e) {
            Toast.makeText(this, "没有正确打开文件管理器", Toast.LENGTH_SHORT).show();
        }
    }

   /* private static void changeAmrToMp3(String sourcePath, String targetPath) {
        File source = new File(sourcePath);
        File target = new File(targetPath);
        AudioAttributes audio = new AudioAttributes();
        Encoder encoder = new Encoder();

        audio.setCodec("libmp3lame");
        EncodingAttributes attrs = new EncodingAttributes();
        attrs.setFormat("mp3");
        attrs.setAudioAttributes(audio);

        try {
            encoder.encode(source, target, attrs);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InputFormatException e) {
            e.printStackTrace();
        } catch (EncoderException e) {
            e.printStackTrace();
        }

        Log.e(TAG, "chang to mp3");
    }*/

    public void ondestroy() {
        super.onDestroy();


        WebChatIM.WebChatAndroid.getInstance().ondisconnect("message", mylisetenr);

    }

    private List<String> getVideoFromSDCard(Context context) {
        Videolist = new ArrayList<>();
        String[] projection = new String[]{MediaStore.Video.Media.DATA, MediaStore.Video.Media
                .DURATION};
        Cursor cursor = context.getContentResolver().query(
                MediaStore.Video.Media.EXTERNAL_CONTENT_URI, projection, null,
                null, null);
        while (cursor.moveToNext()) {
            String path = cursor
                    .getString(cursor
                            .getColumnIndexOrThrow(MediaStore.Video.Media.DATA));
            long duration = cursor
                    .getInt(cursor
                            .getColumnIndexOrThrow(MediaStore.Video.Media.DURATION));


            Videolist.add(path);
        }
        cursor.close();
        return Videolist;
    }

    class Recorder {
        float time;
        String filePathString;

        public Recorder(float time, String filePathString) {
            super();
            this.time = time;
            this.filePathString = filePathString;
        }

        public float getTime() {
            return time;
        }

        public void setTime(float time) {
            this.time = time;
        }

        public String getFilePathString() {
            return filePathString;
        }

        public void setFilePathString(String filePathString) {
            this.filePathString = filePathString;
        }

    }


    public List<EntityVideo> getList(Context context) {
        sysVideoList = new ArrayList<>();
        // MediaStore.Video.Thumbnails.DATA:视频缩略图的文件路径
        String[] thumbColumns = {MediaStore.Video.Thumbnails.DATA,
                MediaStore.Video.Thumbnails.VIDEO_ID};
        // 视频其他信息的查询条件
        String[] mediaColumns = {MediaStore.Video.Media._ID,
                MediaStore.Video.Media.DATA, MediaStore.Video.Media.DURATION};

        Cursor cursor = context.getContentResolver().query(MediaStore.Video.Media
                        .EXTERNAL_CONTENT_URI,
                mediaColumns, null, null, null);

        if (cursor == null) {
            return sysVideoList;
        }
        if (cursor.moveToFirst()) {
            do {
                EntityVideo info = new EntityVideo();
                int id = cursor.getInt(cursor
                        .getColumnIndex(MediaStore.Video.Media._ID));
                Cursor thumbCursor = context.getContentResolver().query(
                        MediaStore.Video.Thumbnails.EXTERNAL_CONTENT_URI,
                        thumbColumns, MediaStore.Video.Thumbnails.VIDEO_ID
                                + "=" + id, null, null);
                if (thumbCursor.moveToFirst()) {
                    info.setPath(thumbCursor.getString(thumbCursor
                            .getColumnIndex(MediaStore.Video.Thumbnails.DATA)));

                    Log.e(TAG, "AAA   " + info.getPath());
                }

                info.setDuration(cursor.getInt(cursor.getColumnIndexOrThrow(MediaStore.Video
                        .Media.DURATION)));
                sysVideoList.add(info);


            } while (cursor.moveToNext());
        }
        return sysVideoList;
    }

}
